<?php

declare(strict_types=1);

namespace app\system\controller;

use app\system\model\Post;
use app\system\model\LogOperate as Log;
use app\system\model\Role;
use app\system\model\RoleDept;
use app\system\model\RoleMenu;
use app\system\model\Dept;
use app\admin\model\Admin;
use app\apps\BaseAppController;

define('APP_TAG', 'company');

/**
 * 公司管理 (小程序API)
 */
class Api extends BaseAppController
{
    //--------------------成员-----------------------//

    /**
     * 读取成员信息列表
     */
    public function user()
    {
        $dept_id = $this->data['dept_id'];
        $obj = new Admin;
        if ($dept_id) {
            $arr = Dept::getDeptId($dept_id);
            $obj = $obj->where('dept_id', 'in', $arr);
        }
        $list = $obj->with(['dept', 'role', 'job'])->order('id', 'desc')->select();
        $new = [];
        foreach ($list as $value) {
            $new[] = [
                'id' => $value['id'],
                'nickname' => $value['nickname'],
                'phone' => $value['phone'],
                'dept_name' => $value['dept'] ? $value['dept']['name'] : '',
                'role_name' => $value['id'] == 1 ? '超级管理员' : ($value['role'] ? $value['role']['name'] : ''),
                'job_name' => $value['job'] ? $value['job']['name'] : '',
                'status' => $value['status'],
            ];
        }
        return json([
            'users' => $new,
            'depts' => Dept::getTrees(),
        ]);
    }

    /**
     * 成员选项
     */
    public function userOptions()
    {
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        $query = [
            'roles' => Role::where('status', 0)->column('name', 'id'),
            'jobs' => Post::where('status', 0)->column('name', 'id'),
            'depts' => Dept::getTrees(),
            'column' => Dept::where('status', 0)->column('name', 'id'),
        ];
        if ($id) {
            $one = Admin::with(['dept', 'role', 'job'])->find($id);
            $query['user'] = [
                'id' => $one['id'],
                'nickname' => $one['nickname'],
                'phone' => $one['phone'],
                'dept_id' => $one['dept_id'],
                'dept_name' => $one['dept'] ? $one['dept']['name'] : '',
                'username' => $one['username'],
                'role_id' => $one['role_id'],
                'role_name' => $one['id'] == 1 ? '超级管理员' : ($one['role'] ? $one['role']['name'] : ''),
                'job_id' => $one['job_id'],
                'job_name' => $one['job'] ? $one['job']['name'] : '',
                'status' => $one['status'],
            ];
        }
        return json($query);
    }

    /**
     * 新增成员信息
     */
    public function userAdd()
    {
        return $this->userPost();
    }

    /**
     * 保存成员信息
     */
    private function userPost()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        $dept_id = (int)$this->data['dept_id'];
        if ($dept_id <= 0) {
            return json(['msg' => '部门不能为空']);
        }
        $dept_name = $this->data['dept_name'];
        $role_id = (int)$this->data['role_id'];
        $role_name = $this->data['role_name'];
        $job_id = (int)$this->data['job_id'];
        $job_name = $this->data['job_name'];
        $username = $this->data['username'];
        if (empty($username)) {
            return json(['msg' => '账号不能为空']);
        }
        $nickname = $this->data['nickname'];
        if (empty($nickname)) {
            return json(['msg' => '姓名不能为空']);
        }
        $phone = $this->data['phone'];
        if (empty($phone)) {
            return json(['msg' => '手机号码不能为空']);
        }
        $password = $this->data['password'];
        if ($id == 0 && empty($password)) {
            return json(['msg' => '密码不能为空']);
        }
        $check1 = Admin::where('username', $username)->find();
        if ($check1 && ($id == 0 || $check1['id'] != $id)) {
            return json(['msg' => '账号已存在']);
        }
        $check2 = Admin::where('phone', $phone)->find();
        if ($check2 && ($id == 0 || $check2['id'] != $id)) {
            return json(['msg' => '手机号码已存在']);
        }
        if ($id) {
            $title = '编辑用户';
            $obj = Admin::find($id);
        } else {
            $title = '新增用户';
            $obj = new Admin;
        }
        if ($password) {
            $obj->password = password_hash($password, PASSWORD_DEFAULT);
        }
        if (isset($this->data['status'])) {
            $obj->status = (bool)$this->data['status'] ? 0 : 1;
        }
        $obj->username = $username;
        $obj->nickname = $nickname;
        $obj->phone = $phone;
        $obj->dept_id = $dept_id;
        $obj->role_id = $role_id;
        $obj->job_id = $job_id;
        $obj->save();
        Log::add($title, [
            'ID' => $obj->id,
            '登录账户' => $username,
            '昵称' => $nickname,
            '手机' => $phone,
            '部门' => $dept_name,
            '角色' => $role_name,
            '岗位' => $job_name,
        ]);
        return json(['msg' => '']);
    }

    /**
     * 编辑成员信息
     */
    public function userEdit()
    {
        return $this->userPost();
    }

    /**
     * 删除成员信息
     */
    public function userRemove()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = $this->data['id'];
        $obj = Admin::find($id);
        $obj->delete();
        Log::add('删除用户', [
            'ID' => $id,
            '登录账号' => $obj->username,
            '昵称' => $obj->nickname,
            '手机号码' => $obj->phone,
        ]);
        return json(['msg' => '']);
    }

    //--------------------岗位-----------------------//

    /**
     * 读取岗位信息列表
     */
    public function job()
    {
        $list = Post::order(['sort' => 'asc', 'id' => 'desc'])->select();
        return json($list);
    }

    /**
     * 新增岗位信息
     */
    public function jobAdd()
    {
        return $this->jobPost();
    }

    /**
     * 保存岗位信息
     */
    private function jobPost()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        $name = $this->data['name'];
        if (empty($name)) {
            return json(['msg' => '岗位名称不能为空']);
        }
        $code = $this->data['code'];
        if (empty($code)) {
            return json(['msg' => '岗位编码不能为空']);
        }
        $sort = (int)$this->data['sort'];
        if ($id) {
            $title = '编辑岗位';
            $obj = Post::find($id);
        } else {
            $title = '新增岗位';
            $obj = new Post;
        }
        if (isset($this->data['status'])) {
            $obj->status = (bool)$this->data['status'] ? 0 : 1;
        }
        $obj->name = $name;
        $obj->code = $code;
        $obj->sort = $sort;
        $obj->update_by = USERNAME;
        $obj->save();
        Log::add($title, [
            'ID' => $obj->id,
            '岗位编码' => $code,
            '岗位名称' => $name,
            '显示顺序' => $sort,
            '备注' => '',
        ]);
        return json(['msg' => '']);
    }

    /**
     * 编辑岗位信息
     */
    public function jobEdit()
    {
        return $this->jobPost();
    }

    /**
     * 删除岗位信息
     */
    public function jobRemove()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = $this->data['id'];
        $obj = Post::find($id);
        $obj->delete();
        Log::add('删除岗位', [
            'ID' => $id,
            '岗位编码' => $obj->code,
            '岗位名称' => $obj->name,
            '显示顺序' => $obj->sort,
            '备注' => $obj->remark,
        ]);
        return json(['msg' => '']);
    }

    //--------------------角色-----------------------//

    /**
     * 读取角色信息列表
     */
    public function role()
    {
        $list = Role::order(['sort' => 'asc', 'id' => 'desc'])->select();
        $arr = Role::dataScope();
        $new = [];
        foreach ($arr as $key => $value) {
            $new[] = [
                'id' => $key,
                'name' => $value,
            ];
        }
        return json(['items' => $list, 'scope' => $new]);
    }

    /**
     * 新增角色信息
     */
    public function roleAdd()
    {
        return $this->rolePost();
    }

    /**
     * 保存角色信息
     */
    private function rolePost()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        $name = $this->data['name'];
        if (empty($name)) {
            return json(['msg' => '角色名称不能为空']);
        }
        $sort = (int)$this->data['sort'];
        $scope_id = (int)$this->data['scope_id'];
        $arr = Role::dataScope();
        if (!isset($arr[$scope_id])) {
            return json(['msg' => '数据权限不存在']);
        }
        if ($id) {
            $title = '编辑角色';
            $obj = Role::find($id);
        } else {
            $title = '新增角色';
            $obj = new Role;
        }
        if (isset($this->data['status'])) {
            $obj->status = (bool)$this->data['status'] ? 0 : 1;
        }
        $obj->data_scope = $scope_id;
        $obj->name = $name;
        $obj->sort = $sort;
        $obj->update_by = USERNAME;
        $obj->save();
        Log::add($title, [
            'ID' => $obj->id,
            '角色名称' => $name,
            '显示顺序' => $sort,
            '数据权限' => $arr[$scope_id],
        ]);
        return json(['msg' => '']);
    }

    /**
     * 编辑角色信息
     */
    public function roleEdit()
    {
        return $this->rolePost();
    }

    /**
     * 删除角色信息
     */
    public function roleRemove()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = $this->data['id'];
        $obj = Role::find($id);
        $arr = Role::dataScope();
        Log::add('删除角色', [
            'ID' => $id,
            '角色名称' => $obj->name,
            '显示顺序' => $obj->sort,
            '数据权限' => $arr[$obj->data_scope],
        ]);
        $obj->delete();
        // 删除菜单与数据权限
        RoleDept::destroy(function($query) use ($id){
            $query->where('role_id', $id);
        });
        RoleMenu::destroy(function($query) use ($id){
            $query->where('role_id', $id);
        });
        return json(['msg' => '']);
    }

    //--------------------部门-----------------------//

    /**
     * 读取部门信息列表
     */
    public function dept()
    {
        $tree = Dept::order(['sort' => 'asc', 'id' => 'desc'])->select();
        $tree = generateTree($tree, 0, []);
        return json($tree);
    }

    /**
     * 读取部门与成员选项
     */
    public function deptOptions()
    {
        $query = [
            'users' => Admin::where('status', 0)->column('nickname', 'id'),
            'depts' => Dept::getTrees(),
            'column' => Dept::where('status', 0)->column('name', 'id'),
        ];
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        if ($id) {
            $query['dept'] = Dept::find($id);
        }
        return json($query);
    }

    /**
     * 新增部门信息
     */
    public function deptAdd()
    {
        return $this->deptPost();
    }

    /**
     * 保存部门信息
     */
    private function deptPost()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $pid = (int)$this->data['dept_id'];
        $name = $this->data['name'];
        if (empty($name)) {
            return json(['msg' => '部门名称不能为空']);
        }
        $sort = (int)$this->data['sort'];
        $admin_id = (int)$this->data['admin_id'];
        $id = isset($this->data['id']) ? $this->data['id'] : 0;
        if ($id) {
            $title = '编辑部门';
            $obj = Dept::find($id);
        } else {
            $title = '新增部门';
            $obj = new Dept;
        }
        if (isset($this->data['status'])) {
            $obj->status = (bool)$this->data['status'] ? 0 : 1;
        }
        $obj->pid = $pid;
        $obj->name = $name;
        $obj->sort = $sort;
        $obj->admin_id = $admin_id;
        $obj->update_by = USERNAME;
        $obj->icon = '';
        $obj->save();
        $admin = Admin::find($admin_id);
        Log::add($title, [
            'ID' => $obj->id,
            '部门名称' => $name,
            '负责人' => $admin ? $admin->nickname : '-',
            '图标' => '',
            '显示顺序' => $sort,
        ]);
        return json(['msg' => '']);
    }

    /**
     * 编辑部门信息
     */
    public function deptEdit()
    {
        return $this->deptPost();
    }

    /**
     * 删除部门信息
     */
    public function deptRemove()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = $this->data['id'];
        $count = Dept::where('pid', $id)->count();
        if ($count) {
            return json(['msg' => '该部门下存在子部门']);
        }
        $obj = Dept::find($id);
        $obj->delete();
        Log::add('删除部门', [
            'ID' => $id,
            '部门名称' => $obj->name,
            '显示顺序' => $obj->sort,
        ]);
        return json(['msg' => '']);
    }
}
